﻿using ComLib.ComType;
using LogLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace DetectProcessing
{
    public class QuoteClient
    {
        public string ServerName { get; set; } = "localhost";

        public int Port { get; set; } = 5678;

        private TcpClient _client = null;

        public string ReceviedData { get; private set; }

        public event EventHandler Closed;
        private void OnClosed()
        {
            Closed?.Invoke(this, new EventArgs());
        }


        public event DataReceivedEventHandler DataReceived;
        private void OnDataReceived()
        {
            DataReceived?.Invoke(this, new DataReceivedEventArgs(this.ReceviedData));
        }

        public QuoteClient(string serName, int port)
        {
            ServerName = serName;
            Port = port;
        }

        public async Task<bool> Connect()
        {           
            _client = new TcpClient();
            try
            {
                await _client.ConnectAsync(ServerName, Port);
                Log.WriteAsync($"客户端{_client.Client.Handle}连接成功!");
                return true;
            }
            catch (SocketException ex)
            {
                Log.WriteException(ex.ToString());
                return false;
            }               
        }

        public async Task SendDataAsync(string message)
        {
            if(_client == null)
            {
                return;
            }
            if(!_client.Connected)
            {
                return;
            }
            try
            {
                var encoder = new UnicodeEncoding();
                byte[] buffer = encoder.GetBytes(message);
                NetworkStream stream = _client.GetStream();
                stream.Write(buffer, 0, buffer.Length);
                await ReceiveAsync();
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }         
        }

        private const int bufferSize = 1024;

        private async Task ReceiveAsync()
        {
            NetworkStream stream = _client.GetStream();
            try
            {                
                byte[] buffer = new Byte[bufferSize];
                int received = await stream.ReadAsync(buffer, 0, bufferSize);
                if (received <= 0)
                {
                    return;
                }
                ReceviedData = Encoding.Unicode.GetString(buffer).Trim('\0');
                OnDataReceived();
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }
            finally
            {
                stream?.Close();
                OnClosed();
                Disconnect();
            }
        }

        private void Disconnect()
        {
            if(_client.Connected)
            {
                _client.Close();
                Log.WriteAsync($"客户端{_client.Client.Handle}已关闭!");
            }
        }
    }
}
